package com.dsiab.manageService.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.dsiab.manageService.common.CommonUtils;
import com.dsiab.manageService.entity.AccountDto;
import com.dsiab.manageService.entity.PagesDto;
import com.dsiab.manageService.entity.SiteInfoDto;
import com.dsiab.manageService.entity.UserDto;
import com.dsiab.manageService.jwt.JwtAuthService;
import com.dsiab.manageService.mail.MailSenderBoot;
import com.dsiab.manageService.mapper.AccountDao;
import com.dsiab.manageService.mapper.AdminDao;
import com.dsiab.manageService.security.service.GetCurrentLoginUsername;
import com.dsiab.manageService.service.AccountService;
import com.dsiab.manageService.service.ToolsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

  @Autowired
  AccountDao accountDao;

  @Autowired
  AdminDao adminDao;
  @Autowired
  JwtAuthService jwtAuthService;
  @Autowired
  GetCurrentLoginUsername getCurrentLoginUsername;
  @Autowired
  CommonUtils commonUtils;
  @Autowired
  ToolsService toolsService;

  @Autowired
  MailSenderBoot mailSenderBoot;


  public UserDto login(AccountDto accountDto, String ip) throws Exception {

    String username = accountDto.getUsername();
    String password = accountDto.getPassword();
    if (username.isEmpty() || password.isEmpty()){
      throw new Exception("用户名和密码不能为空");
    }

    //加密明文密码后登录
    String encryptedPwd = DigestUtil.md5Hex(password);
    String  token = jwtAuthService.login(username,encryptedPwd);
    UserDto user = accountDao.getLimitedUserByname(username);
    String roleListjoin = commonUtils.getRoleListByString(username);
    user.setRole(roleListjoin);
    user.setToken(token);
    // 写入登入日志
    String address = toolsService.getAddressFromIp(ip,false);
    log.info("ip:"+ip +"_address:" + address);
    accountDao.insertLoginLog(username,ip,address);
    // 新增积分
    addMemberPoints(username);
//    mailSenderBoot.sendMail("2381773226@qq.com","登录通知",username + "登录了系统,ip归属地："+ address);
    // 添加登录通知
    adminDao.addNotice("登录通知",username + "  登录了系统,ip地址为：" + ip + ", ip归属地："+ address);
    return user;
  }

  public void updateUserInfo(AccountDto accountDto) {
    String username = getCurrentLoginUsername.getUsername();
    accountDto.setUsername(username);
    accountDao.updateUserInfo(accountDto);
  }

  public List<UserDto> getUserList(int page) {
    List<UserDto> userList = accountDao.getUserList(page);
    for (UserDto user: userList){
      user.setRole(commonUtils.getRoleListByString(user.getUsername()));
    }
    return userList;
  }

  public void insertRole(String username,String roleId) {
    accountDao.insertRole(username,roleId);
  }

  public void deleteRolesByUsername(String username) {
    accountDao.deleteRolesByUsername(username);
  }

  public void deleUser(int id, String username) {
    accountDao.deleUser(id);
    accountDao.deleUserRoles(username);
  }

  public Map getSiteInfo() {
    return accountDao.getSiteInfo();
  }

  public UserDto getUserInfo() {

    String username = getCurrentLoginUsername.getUsername();
    UserDto user = accountDao.getLimitedUserByname(username);
    // 查询角色
    String roleListjoin = commonUtils.getRoleListByString(username);
    user.setRole(roleListjoin);
    // 随机查询每日一句
    PagesDto pagesDto = accountDao.getDailySentence();
    user.setDailySentence(pagesDto.getContent());
    return  user;
  }

  public void updateSiteInfo(SiteInfoDto siteInfoDto) {
    accountDao.updateSiteInfo(siteInfoDto);
  }

  public void register(Map map) throws Exception {
    String username = (String) map.get("username");
    String password = (String) map.get("password");
    String email = (String) map.get("email");
    try {
      //加密明文密码
      String encryptedPwd = DigestUtil.md5Hex(password);
      accountDao.insertUser(username,encryptedPwd,email);
    } catch (Exception e){
      log.info("注册账号新增失败：" + e.toString());
      throw new Exception("注册失败");
    }

    // 设置邮箱验证
    String uid = UUID.randomUUID().toString();
    accountDao.setEmailValidteUrl(username,email,uid);
    try {
      Map<String,Object> formData = new HashMap<>();
      formData.put("UserName",username);
      formData.put("validUrl","http://admin.dsiab.com/#/regActive?id=" + uid);
      mailSenderBoot.sendMailByTemplate(email,"注册成功通知" ,formData,"register.ftl");
    } catch (Exception e){
      log.info("注册邮件通知发送失败：" + e.toString());
    }
    // 新注册用户默认给作者权限
    accountDao.insertRole(username,"ROLE_author");
    // 添加默认分类
    accountDao.insertDefaultCate(username,"未分类",1);
    Map siteInfo = accountDao.getSiteInfo();
    adminDao.addNotice("注册通知",username + "注册了账号");
//    mailSenderBoot.sendMail((String)siteInfo.get("siteEmail"), username + "注册了账号", "注册通知");
  }

  public void getValidEmailEffective(String id) {
    // 邮箱验证
    accountDao.getValidEmailEffective(id);
  }
  public void addMemberPoints(String username){
    accountDao.addMemberPoints(username,"login", 10);
    accountDao.updateMemberPoints(username, 10);
  }
}